// ContentView.swift
import SwiftUI
import Network
import SystemConfiguration.CaptiveNetwork
import UIKit
import Combine

struct ContentView: View {
    @StateObject private var proxyServer = ProxyServer()
    @StateObject private var networkInfo = NetworkInfo()
    @StateObject private var logger = Logger()
    
    @State private var showInstructions = false
    @State private var showLogs = false
    @State private var customPort: String = "8080"
    @State private var testConnectionResult: String?
    @State private var isTestingConnection = false
    
    var body: some View {
        NavigationView {
            ScrollView {
                VStack(spacing: 20) {
                    
                    // 标题区域
                    headerSection
                    
                    // 代理状态区域
                    statusSection
                    
                    // 端口设置区域
                    portSettingsSection
                    
                    // 网络信息区域
                    networkInfoSection
                    
                    // 系统信息区域
                    systemInfoSection
                    
                    // VPN状态区域
                    vpnStatusSection
                    
                    // 测试连接区域
                    testConnectionSection
                    
                    // 控制按钮区域
                    controlSection
                    
                    // 使用说明和日志按钮
                    actionButtonsSection
                }
                .padding()
            }
            .background(
                Image("launch")
                               .resizable()
                               .scaledToFill()
                               .ignoresSafeArea()
            )
            .navigationTitle("龚婷婷 Proxy")
            .foregroundStyle(.pink)
            .navigationBarTitleDisplayMode(.inline)
            .sheet(isPresented: $showInstructions) {
                InstructionsView()
            }
            .sheet(isPresented: $showLogs) {
                LogView(logger: logger)
            }
            .onAppear {
                
                networkInfo.updateNetworkInfo()
                // 开始定期检查VPN状态
                networkInfo.startVPNMonitoring()
            }
            .onDisappear {
                networkInfo.stopVPNMonitoring()
            }
        }
    }
    
    // 标题区域
    var headerSection: some View {
        VStack {
            
            Image(systemName: "network")
                .resizable()
                .scaledToFit()
                .frame(width: 60, height: 60)
    
                .foregroundColor(.yellow)
            
            Text("Proxy")
                .font(.title2)
                .fontWeight(.bold)
                .foregroundColor(.yellow)
            
            Text("将PC流量通过iOS设备转发")
                .font(.subheadline)
                .foregroundColor(.yellow)
        }
    }
    
    // 代理状态区域
    var statusSection: some View {
        VStack(spacing: 10) {
            HStack {
                Circle()
                    .fill(proxyServer.isRunning ? Color.green : Color.red)
                    .frame(width: 12, height: 12)
                Text(proxyServer.isRunning ? "代理运行中" : "代理已停止")
                    .font(.headline)
            }
            
            if let localIP = networkInfo.localIP {
                VStack(spacing: 5) {
                    Text("代理地址: \(localIP):\(proxyServer.port)")
                        .font(.system(.body, design: .monospaced))
                    
                    Text("在PC上设置代理为此地址")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
            }
            
            if let errorMessage = proxyServer.errorMessage {
                Text("错误: \(errorMessage)")
                    .font(.caption)
                    .foregroundColor(.red)
                    .padding(8)
                    .background(Color.red.opacity(0.1))
                    .cornerRadius(8)
            }
        }
        .padding()
        .frame(maxWidth: .infinity)
        .background(Color.white.opacity(0.3))
        .cornerRadius(12)
    }
    
    // 端口设置区域
    var portSettingsSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Image(systemName: "number")
                Text("端口设置")
                    .font(.headline)
            }
            
            HStack {
                TextField("端口号", text: $customPort)
                    .keyboardType(.numberPad)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .onChange(of: customPort) { newValue in
                        // 验证端口号
                        if let port = Int(newValue), port > 0 && port <= 65535 {
                            proxyServer.port = port
                        }
                    }
                
                Button("应用") {
                    if let port = Int(customPort), port > 0 && port <= 65535 {
                        proxyServer.port = port
                        if proxyServer.isRunning {
                            proxyServer.stop()
                            proxyServer.start()
                        }
                    } else {
                        // 恢复有效端口
                        customPort = "\(proxyServer.port)"
                    }
                }
                .disabled(proxyServer.isRunning)
            }
            
            Text("端口范围: 1-65535")
                .font(.caption)
                .foregroundColor(.secondary)
        }
        .padding()
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(Color.white.opacity(0.3))
        .cornerRadius(12)
    }
    
    // 网络信息区域
    var networkInfoSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Image(systemName: "wifi")
                Text("网络信息")
                    .font(.headline)
            }
            
            if let ssid = networkInfo.wifiSSID {
                InfoRow(title: "WiFi名称", value: ssid)
            }
            
            if let ip = networkInfo.localIP {
                InfoRow(title: "本地IP", value: ip)
            }
            
            if let netmask = networkInfo.netmask {
                InfoRow(title: "子网掩码", value: netmask)
            }
            
            if let router = networkInfo.routerIP {
                InfoRow(title: "路由器IP", value: router)
            }
            
            InfoRow(title: "网络类型", value: networkInfo.networkType)
        }
        .padding()
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(Color.white.opacity(0.3))
        .cornerRadius(12)
    }
    
    // 系统信息区域
    var systemInfoSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Image(systemName: "info.circle")
                Text("系统信息")
                    .font(.headline)
            }
            
            InfoRow(title: "设备型号", value: networkInfo.deviceModel)
            InfoRow(title: "系统版本", value: networkInfo.systemVersion)
            InfoRow(title: "应用版本", value: networkInfo.appVersion)
        }
        .padding()
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(Color.white.opacity(0.3))
        .cornerRadius(12)
    }
    
    // VPN状态区域
    var vpnStatusSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Image(systemName: "lock.shield")
                Text("VPN状态")
                    .font(.headline)
            }
            
            HStack {
                Circle()
                    .fill(networkInfo.isVPNConnected ? Color.green : Color.gray)
                    .frame(width: 12, height: 12)
                Text(networkInfo.isVPNConnected ? "VPN已连接" : "VPN未连接")
            }
            
            if networkInfo.isVPNConnected, let vpnIP = networkInfo.vpnIP {
                InfoRow(title: "VPN IP", value: vpnIP)
            }
        }
        .padding()
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(Color.white.opacity(0.3))
        .cornerRadius(12)
    }
    
    // 测试连接区域
    var testConnectionSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Image(systemName: "link")
                Text("测试连接")
                    .font(.headline)
            }
            
            Button(action: {
                testGoogleConnection()
            }) {
                HStack {
                    if isTestingConnection {
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle())
                            .scaleEffect(0.8)
                    } else {
                        Image(systemName: "arrow.clockwise")
                    }
                    Text("测试连接到 Google")
                }
                .foregroundColor(.white)
                .padding()
                .frame(maxWidth: .infinity)
                .background(Color.blue.opacity(0.7))
                .cornerRadius(10)
            }
            .disabled(isTestingConnection)
            
            if let result = testConnectionResult {
                Text(result)
                    .font(.caption)
                    .padding(8)
                    .background(result.contains("成功") ? Color.green.opacity(0.1) : Color.red.opacity(0.1))
                    .cornerRadius(8)
            }
        }
        .padding()
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(Color.white.opacity(0.3))
        .cornerRadius(12)
    }
    
    // 控制按钮区域
    var controlSection: some View {
        VStack(spacing: 15) {
            Button(action: {
                if proxyServer.isRunning {
                    proxyServer.stop()
                } else {
                    proxyServer.start()
                }
            }) {
                HStack {
                    Image(systemName: proxyServer.isRunning ? "stop.circle" : "play.circle")
                    Text(proxyServer.isRunning ? "停止代理" : "启动代理")
                }
                .foregroundColor(.white)
                .padding()
                .frame(maxWidth: .infinity)
                .background(proxyServer.isRunning ? Color.red.opacity(0.7) : Color.blue.opacity(0.7))
                .cornerRadius(10)
            }
            
            Button(action: {
                networkInfo.updateNetworkInfo()
            }) {
                HStack {
                    Image(systemName: "arrow.clockwise")
                    Text("刷新网络信息")
                }
                .foregroundColor(.blue)
                .padding()
                .frame(maxWidth: .infinity)
                .background(Color(.secondarySystemBackground))
                .cornerRadius(10)
            }
        }
    }
    
    // 使用说明和日志按钮
    var actionButtonsSection: some View {
        HStack(spacing: 20) {
            Button(action: {
                showInstructions = true
            }) {
                HStack {
                    Image(systemName: "questionmark.circle")
                    Text("使用说明")
                }
                .foregroundColor(.blue)
            }
            
            Button(action: {
                showLogs = true
            }) {
                HStack {
                    Image(systemName: "doc.text")
                    Text("查看日志")
                }
                .foregroundColor(.blue)
            }
        }
        .padding(.top, 10)
    }
    
    // 测试Google连接
    private func testGoogleConnection() {
        isTestingConnection = true
        testConnectionResult = nil
        
        let url = URL(string: "https://www.google.com")!
        var request = URLRequest(url: url)
        request.timeoutInterval = 10
        
        let session = URLSession.shared
        let task = session.dataTask(with: request) { data, response, error in
            DispatchQueue.main.async {
                self.isTestingConnection = false
                
                if let error = error {
                    self.testConnectionResult = "连接失败: \(error.localizedDescription)"
                    self.logger.addLog("测试连接失败: \(error.localizedDescription)")
                } else if let httpResponse = response as? HTTPURLResponse {
                    if httpResponse.statusCode == 200 {
                        self.testConnectionResult = "连接成功! 状态码: \(httpResponse.statusCode)"
                        self.logger.addLog("测试连接成功: 状态码 \(httpResponse.statusCode)")
                    } else {
                        self.testConnectionResult = "连接异常! 状态码: \(httpResponse.statusCode)"
                        self.logger.addLog("测试连接异常: 状态码 \(httpResponse.statusCode)")
                    }
                } else {
                    self.testConnectionResult = "连接未知响应"
                    self.logger.addLog("测试连接未知响应")
                }
            }
        }
        
        logger.addLog("开始测试连接到 https://www.google.com")
        task.resume()
    }
}

// 信息行组件
struct InfoRow: View {
    let title: String
    let value: String
    
    var body: some View {
        HStack {
            Text(title)
                .foregroundColor(.secondary)
            Spacer()
            Text(value)
                .font(.system(.body, design: .monospaced))
        }
    }
}

// 使用说明视图
struct InstructionsView: View {
    var body: some View {
        NavigationView {
            ScrollView {
                VStack(alignment: .leading, spacing: 20) {
                    Text("使用说明")
                        .font(.title2)
                        .fontWeight(.bold)
                        .padding(.bottom, 5)
                    
                    InstructionStep(
                        number: 1,
                        title: "启动代理",
                        description: "点击主界面上的「启动代理」按钮，等待代理服务运行"
                    )
                    
                    InstructionStep(
                        number: 2,
                        title: "查看代理地址",
                        description: "记下显示的代理地址（格式为 IP:端口）"
                    )
                    
                    InstructionStep(
                        number: 3,
                        title: "配置PC代理",
                        description: "在PC的网络设置中配置HTTP代理，地址为iOS应用显示的IP和端口"
                    )
                    
                    InstructionStep(
                        number: 4,
                        title: "验证连接",
                        description: "在PC上打开浏览器访问网站，流量将通过iOS设备转发"
                    )
                    
                    VStack(alignment: .leading, spacing: 10) {
                        Text("注意事项")
                            .font(.headline)
                        
                        Text("• 确保PC和iOS设备在同一WiFi网络下")
                        Text("• 免费开发者账号限制：应用切换到后台时代理可能会断开")
                        Text("• 某些网络可能阻止代理连接，请检查网络设置")
                        Text("• 可以自定义端口号，但需要确保端口未被占用")
                    }
                    .padding()
                    .background(Color.yellow.opacity(0.1))
                    .cornerRadius(10)
                }
                .padding()
            }
            .navigationTitle("使用说明")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("完成") {
                        // 通过环境变量关闭sheet
                    }
                }
            }
        }
    }
}

// 日志视图
struct LogView: View {
    @ObservedObject var logger: Logger
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        NavigationView {
            VStack {
                ScrollViewReader { proxy in
                    ScrollView {
                        LazyVStack(alignment: .leading, spacing: 8) {
                            ForEach(logger.logs) { log in
                                Text("\(log.timestamp, formatter: logDateFormatter): \(log.message)")
                                    .font(.system(.caption, design: .monospaced))
                                    .foregroundColor(.primary)
                                    .textSelection(.enabled)
                                    .id(log.id)
                            }
                        }
                        .padding()
                    }
                    .onChange(of: logger.logs.count) { _ in
                        if let lastLog = logger.logs.last {
                            withAnimation {
                                proxy.scrollTo(lastLog.id, anchor: .bottom)
                            }
                        }
                    }
                }
                
                HStack {
                    Button("清空日志") {
                        logger.clearLogs()
                    }
                    .padding()
                    
                    Spacer()
                    
                    Button("关闭") {
                        presentationMode.wrappedValue.dismiss()
                    }
                    .padding()
                }
                .background(Color(.secondarySystemBackground))
            }
            .navigationTitle("代理日志")
            .navigationBarTitleDisplayMode(.inline)
        }
    }
}

// 使用说明步骤组件
struct InstructionStep: View {
    let number: Int
    let title: String
    let description: String
    
    var body: some View {
        HStack(alignment: .top) {
            Text("\(number)")
                .font(.caption)
                .fontWeight(.bold)
                .foregroundColor(.white)
                .frame(width: 24, height: 24)
                .background(Circle().fill(Color.blue))
            
            VStack(alignment: .leading, spacing: 5) {
                Text(title)
                    .font(.headline)
                Text(description)
                    .font(.body)
                    .foregroundColor(.secondary)
            }
        }
    }
}

// 日志模型
struct LogEntry: Identifiable {
    let id = UUID()
    let timestamp: Date
    let message: String
}

// 日志管理器
class Logger: ObservableObject {
    @Published var logs: [LogEntry] = []
    private let maxLogCount = 1000
    
    func addLog(_ message: String) {
        DispatchQueue.main.async {
            let newLog = LogEntry(timestamp: Date(), message: message)
            self.logs.append(newLog)
            
            // 限制日志数量
            if self.logs.count > self.maxLogCount {
                self.logs.removeFirst(self.logs.count - self.maxLogCount)
            }
        }
    }
    
    func clearLogs() {
        DispatchQueue.main.async {
            self.logs.removeAll()
        }
    }
}

// 日期格式化器
let logDateFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateFormat = "HH:mm:ss"
    return formatter
}()

// 网络信息类
class NetworkInfo: ObservableObject {
    @Published var wifiSSID: String?
    @Published var localIP: String?
    @Published var netmask: String?
    @Published var routerIP: String?
    @Published var vpnIP: String?
    @Published var isVPNConnected: Bool = false
    @Published var networkType: String = "未知"
    
    let deviceModel: String
    let systemVersion: String
    let appVersion: String
    
    private var vpnTimer: Timer?
    
    init() {
        // 获取设备信息
        let device = UIDevice.current
        deviceModel = device.model
        systemVersion = "\(device.systemName) \(device.systemVersion)"
        
        // 获取应用版本
        if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String,
           let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
            appVersion = "\(version) (\(build))"
        } else {
            appVersion = "未知"
        }
        
        updateNetworkInfo()
        checkVPNConnection()
    }
    
    func updateNetworkInfo() {
        // 获取WiFi SSID (需要权限)
        wifiSSID = getWiFiSSID()
        
        // 获取IP地址信息
        getLocalIPInfo()
        
        // 确定网络类型
        networkType = wifiSSID != nil ? "WiFi" : "蜂窝数据"
        
        // 检查VPN连接
        checkVPNConnection()
    }
    
    func startVPNMonitoring() {
        // 每5秒检查一次VPN状态
        vpnTimer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { [weak self] _ in
            self?.checkVPNConnection()
        }
    }
    
    func stopVPNMonitoring() {
        vpnTimer?.invalidate()
        vpnTimer = nil
    }
    
    private func checkVPNConnection() {
        // 检查VPN连接状态
        guard let settings = CFNetworkCopySystemProxySettings()?.takeRetainedValue(),
              let dict = settings as? [String: Any] else {
            DispatchQueue.main.async {
                self.isVPNConnected = false
                self.vpnIP = nil
            }
            return
        }
        
        // 检查是否有HTTP或HTTPS代理设置
        if let httpProxy = dict["HTTPProxy"] as? String, !httpProxy.isEmpty {
            DispatchQueue.main.async {
                self.isVPNConnected = true
                self.vpnIP = httpProxy
            }
            return
        }
        
        if let httpsProxy = dict["HTTPSProxy"] as? String, !httpsProxy.isEmpty {
            DispatchQueue.main.async {
                self.isVPNConnected = true
                self.vpnIP = httpsProxy
            }
            return
        }
        
        // 检查网络接口获取VPN IP
        var ifaddr: UnsafeMutablePointer<ifaddrs>?
        guard getifaddrs(&ifaddr) == 0 else {
            DispatchQueue.main.async {
                self.isVPNConnected = false
                self.vpnIP = nil
            }
            return
        }
        
        var vpnDetected = false
        var vpnAddress: String?
        
        var ptr = ifaddr
        while ptr != nil {
            defer { ptr = ptr?.pointee.ifa_next }
            
            let interface = ptr?.pointee
            let addrFamily = interface?.ifa_addr.pointee.sa_family
            if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
                let name = String(cString: (interface?.ifa_name)!)
                
                // 常见的VPN接口名称
                if name.contains("utun") || name.contains("tap") || name.contains("tun") || name.contains("ppp") {
                    vpnDetected = true
                    
                    // 获取VPN IP地址
                    var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                    getnameinfo(interface?.ifa_addr, socklen_t((interface?.ifa_addr.pointee.sa_len)!),
                                &hostname, socklen_t(hostname.count),
                                nil, socklen_t(0), NI_NUMERICHOST)
                    vpnAddress = String(cString: hostname)
                    break
                }
            }
        }
        
        freeifaddrs(ifaddr)
        
        DispatchQueue.main.async {
            self.isVPNConnected = vpnDetected
            self.vpnIP = vpnAddress
        }
    }
    
    private func getWiFiSSID() -> String? {
        #if targetEnvironment(simulator)
        return "Simulator"
        #else
        guard let interfaces = CNCopySupportedInterfaces() as? [String] else { return nil }
        
        for interface in interfaces {
            guard let interfaceInfo = CNCopyCurrentNetworkInfo(interface as CFString) as? [String: AnyObject] else { continue }
            guard let ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String else { continue }
            return ssid
        }
        
        return nil
        #endif
    }
    
    private func getLocalIPInfo() {
        var address: String?
        var netmask: String?
        var router: String?
        var ifaddr: UnsafeMutablePointer<ifaddrs>?
        
        guard getifaddrs(&ifaddr) == 0 else { return }
        guard let firstAddr = ifaddr else { return }
        
        for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
            let interface = ifptr.pointee
            
            // 检查接口状态和类型
            let addrFamily = interface.ifa_addr.pointee.sa_family
            if addrFamily == UInt8(AF_INET) {
                // 检查接口名称
                let name = String(cString: interface.ifa_name)
                if name == "en0" {
                    // 获取IP地址
                    var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                    getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len),
                                &hostname, socklen_t(hostname.count),
                                nil, socklen_t(0), NI_NUMERICHOST)
                    address = String(cString: hostname)
                    
                    // 获取子网掩码
                    if let ifa_netmask = interface.ifa_netmask {
                        var netmaskName = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                        getnameinfo(ifa_netmask, socklen_t(ifa_netmask.pointee.sa_len),
                                    &netmaskName, socklen_t(netmaskName.count),
                                    nil, socklen_t(0), NI_NUMERICHOST)
                        netmask = String(cString: netmaskName)
                    }
                    
                    // 获取默认网关（简化处理，实际需要更复杂的方法）
                    router = getDefaultGateway()
                }
            }
        }
        
        freeifaddrs(ifaddr)
        
        DispatchQueue.main.async {
            self.localIP = address
            self.netmask = netmask
            self.routerIP = router
        }
    }
    
    private func getDefaultGateway() -> String? {
        // 简化实现，实际获取默认网关需要更复杂的方法
        // 这里返回路由器的常见IP地址
        if let ip = localIP {
            let components = ip.split(separator: ".")
            if components.count == 4 {
                return "\(components[0]).\(components[1]).\(components[2]).1"
            }
        }
        return nil
    }
}

// 代理服务器类
class ProxyServer: ObservableObject {
    private var listener: NWListener?
    private var connections: [NWConnection] = []
    private let queue = DispatchQueue(label: "proxy-server")
    
    @Published var isRunning: Bool = false
    @Published var errorMessage: String?
    @Published var port: Int = 8080
    
    private var logger = Logger()
    
    func start() {
        do {
            // 创建TCP监听器
            let parameters = NWParameters.tcp
            listener = try NWListener(using: parameters, on: NWEndpoint.Port(rawValue: UInt16(port))!)
            
            listener?.stateUpdateHandler = { [weak self] newState in
                guard let self = self else { return }
                
                switch newState {
                case .ready:
                    DispatchQueue.main.async {
                        self.isRunning = true
                        self.errorMessage = nil
                    }
                    self.logger.addLog("代理服务器正在端口 \(self.port) 上运行")
                case .failed(let error):
                    DispatchQueue.main.async {
                        self.isRunning = false
                        self.errorMessage = error.localizedDescription
                    }
                    self.logger.addLog("代理服务器失败: \(error)")
                case .cancelled:
                    DispatchQueue.main.async {
                        self.isRunning = false
                    }
                    self.logger.addLog("代理服务器已取消")
                default:
                    break
                }
            }
            
            listener?.newConnectionHandler = { [weak self] newConnection in
                guard let self = self else { return }
                
                self.logger.addLog("接收到新连接: \(newConnection.endpoint)")
                self.handleConnection(newConnection)
                newConnection.start(queue: self.queue)
            }
            
            listener?.start(queue: queue)
            logger.addLog("正在启动代理服务器，端口: \(port)")
        } catch {
            DispatchQueue.main.async {
                self.errorMessage = error.localizedDescription
            }
            logger.addLog("启动代理服务器时出错: \(error)")
        }
    }
    
    func stop() {
        listener?.cancel()
        connections.forEach { $0.cancel() }
        connections.removeAll()
        isRunning = false
        logger.addLog("代理服务器已停止")
    }
    
    private func handleConnection(_ connection: NWConnection) {
        connections.append(connection)
        
        connection.receive(minimumIncompleteLength: 1, maximumLength: 8192) { [weak self] (data, context, isComplete, error) in
            guard let self = self else { return }
            
            if let data = data, let request = String(data: data, encoding: .utf8) {
                self.logger.addLog("收到请求: \(request.prefix(200))...")
                
                if request.hasPrefix("CONNECT") {
                    self.handleHTTPSConnection(connection, request: request)
                } else {
                    self.handleHTTPConnection(connection, request: request, data: data)
                }
            } else if let error = error {
                self.logger.addLog("接收数据错误: \(error)")
                self.removeConnection(connection)
            }
        }
    }
    
    private func handleHTTPConnection(_ connection: NWConnection, request: String, data: Data) {
        // 提取Host和Port
        guard let host = extractHost(from: request) else {
            self.logger.addLog("无法从请求中提取主机")
            sendBadRequestResponse(connection)
            return
        }
        
        let hostParts = host.split(separator: ":")
        let targetHost = String(hostParts[0])
        let targetPort = hostParts.count > 1 ? Int(String(hostParts[1])) ?? 80 : 80
        
        self.logger.addLog("HTTP代理请求: \(targetHost):\(targetPort)")
        
        // 连接到目标服务器
        let targetConnection = createTargetConnection(host: targetHost, port: targetPort)
        
        targetConnection.stateUpdateHandler = { [weak self] state in
            guard let self = self else { return }
            
            switch state {
            case .ready:
                self.logger.addLog("已连接到目标服务器 \(host)")
                // 发送原始请求数据
                targetConnection.send(content: data, completion: .contentProcessed({ error in
                    if let error = error {
                        self.logger.addLog("发送数据到目标服务器错误: \(error)")
                        self.removeConnection(connection)
                        self.removeConnection(targetConnection)
                    }
                }))
                
                // 开始接收目标服务器的响应
                self.receiveFromTarget(targetConnection, clientConnection: connection)
                
            case .failed(let error):
                self.logger.addLog("连接到目标服务器失败: \(error)")
                self.sendBadGatewayResponse(connection)
                self.removeConnection(connection)
                self.removeConnection(targetConnection)
            default:
                break
            }
        }
        
        targetConnection.start(queue: queue)
    }
    
    private func handleHTTPSConnection(_ clientConnection: NWConnection, request: String) {
        // 提取CONNECT请求中的主机和端口
        let components = request.split(separator: " ")
        guard components.count >= 2, components[0] == "CONNECT" else {
            self.logger.addLog("无效的CONNECT请求")
            sendBadRequestResponse(clientConnection)
            return
        }
        
        let hostPort = String(components[1])
        let hostParts = hostPort.split(separator: ":")
        let targetHost = String(hostParts[0])
        let targetPort = hostParts.count > 1 ? Int(String(hostParts[1])) ?? 443 : 443
        
        self.logger.addLog("HTTPS代理请求: \(targetHost):\(targetPort)")
        
        // 连接到目标服务器
        let targetConnection = createTargetConnection(host: targetHost, port: targetPort)
        
        targetConnection.stateUpdateHandler = { [weak self] state in
            guard let self = self else { return }
            
            switch state {
            case .ready:
                self.logger.addLog("已通过CONNECT连接到目标服务器 \(hostPort)")
                // 发送200 Connection Established响应
                let response = "HTTP/1.1 200 Connection Established\r\n\r\n"
                clientConnection.send(content: response.data(using: .utf8), completion: .contentProcessed({ error in
                    if let error = error {
                        self.logger.addLog("发送CONNECT响应错误: \(error)")
                        self.removeConnection(clientConnection)
                        self.removeConnection(targetConnection)
                    } else {
                        // 开始双向数据转发
                        self.forwardData(between: clientConnection, and: targetConnection)
                    }
                }))
                
            case .failed(let error):
                self.logger.addLog("CONNECT连接到目标服务器失败: \(error)")
                self.sendBadGatewayResponse(clientConnection)
                self.removeConnection(clientConnection)
                self.removeConnection(targetConnection)
            default:
                break
            }
        }
        
        targetConnection.start(queue: queue)
    }
    
    private func forwardData(between client: NWConnection, and target: NWConnection) {
        // 客户端 -> 目标服务器
        client.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] (data, _, _, error) in
            guard let self = self else { return }
            
            if let data = data, !data.isEmpty {
                target.send(content: data, completion: .contentProcessed({ error in
                    if let error = error {
                        self.logger.addLog("发送数据到目标服务器错误: \(error)")
                        self.removeConnection(client)
                        self.removeConnection(target)
                    } else {
                        self.forwardData(between: client, and: target)
                    }
                }))
            } else if let error = error {
                self.logger.addLog("从客户端接收数据错误: \(error)")
                self.removeConnection(client)
                self.removeConnection(target)
            }
        }
        
        // 目标服务器 -> 客户端
        target.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] (data, _, _, error) in
            guard let self = self else { return }
            
            if let data = data, !data.isEmpty {
                client.send(content: data, completion: .contentProcessed({ error in
                    if let error = error {
                        self.logger.addLog("发送数据到客户端错误: \(error)")
                        self.removeConnection(client)
                        self.removeConnection(target)
                    } else {
                        self.forwardData(between: client, and: target)
                    }
                }))
            } else if let error = error {
                self.logger.addLog("从目标服务器接收数据错误: \(error)")
                self.removeConnection(client)
                self.removeConnection(target)
            }
        }
    }
    
    private func receiveFromTarget(_ targetConnection: NWConnection, clientConnection: NWConnection) {
        targetConnection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] (data, _, _, error) in
            guard let self = self else { return }
            
            if let data = data, !data.isEmpty {
                clientConnection.send(content: data, completion: .contentProcessed({ error in
                    if let error = error {
                        self.logger.addLog("发送响应到客户端错误: \(error)")
                        self.removeConnection(clientConnection)
                        self.removeConnection(targetConnection)
                    } else {
                        self.receiveFromTarget(targetConnection, clientConnection: clientConnection)
                    }
                }))
            } else if let error = error {
                self.logger.addLog("从目标服务器接收响应错误: \(error)")
                self.removeConnection(clientConnection)
                self.removeConnection(targetConnection)
            }
        }
    }
    
    private func createTargetConnection(host: String, port: Int) -> NWConnection {
        let host = NWEndpoint.Host(host)
        let port = NWEndpoint.Port(rawValue: UInt16(port))!
        return NWConnection(host: host, port: port, using: .tcp)
    }
    
    private func extractHost(from request: String) -> String? {
        let lines = request.split(separator: "\r\n")
        for line in lines {
            if line.lowercased().starts(with: "host:") {
                let hostLine = line.dropFirst(5).trimmingCharacters(in: .whitespaces)
                return String(hostLine)
            }
        }
        return nil
    }
    
    private func sendBadRequestResponse(_ connection: NWConnection) {
        let response = "HTTP/1.1 400 Bad Request\r\n\r\n"
        connection.send(content: response.data(using: .utf8), completion: .contentProcessed({ _ in
            self.removeConnection(connection)
        }))
    }
    
    private func sendBadGatewayResponse(_ connection: NWConnection) {
        let response = "HTTP/1.1 502 Bad Gateway\r\n\r\n"
        connection.send(content: response.data(using: .utf8), completion: .contentProcessed({ _ in
            self.removeConnection(connection)
        }))
    }
    
    private func removeConnection(_ connection: NWConnection) {
        connection.cancel()
        if let index = connections.firstIndex(where: { $0 === connection }) {
            connections.remove(at: index)
        }
    }
}

#Preview(body: {
    ContentView()
})
